/**
 * Home.java
 * 
 * 04/10/2013
 * 
 * Copyright GPL
 */
package info.victor.servlets;

import info.victor.content.Tale;
import info.victor.utils.AccessDB;
import info.victor.utils.WebUtils;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class Home
 */
@WebServlet("/Home")
public class Home extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor
	 * @see HttpServlet#HttpServlet()
	 */
	public Home() {
		super();
	}

	/**
	 * this receives the GET.
	 * @see HttpServlet#doGet(HttpServletRequest request, 
	 * HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,
					IOException {
		
		showTales(request, response);
	}

	/**
	 * this receives the POST
	 * @see HttpServlet#doPost(HttpServletRequest request, 
	 * HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,
					IOException {
		
		showTales(request, response);
	}

	/**
	 * this shows the tales
	 * @param request
	 * @param response
	 */
	private void showTales(HttpServletRequest request,
			HttpServletResponse response){
		
		//We obtain all the tales. 
		//In the real life only we will obtain 10 tales per page (for example).
		ArrayList<Tale> tales = new AccessDB().getAllTales();
		
		request.setAttribute("tales", talesHtmlCode(tales));
		WebUtils.redirect(this, request, "/home.jsp", response);
	}

	/**
	 * this generates the code HTML for showing the tales
	 * @param tales
	 * @return
	 */
	private String talesHtmlCode(ArrayList<Tale> tales){
		
		int sizetales = tales.size();
		String taleInHtmlCode = "";
		
		//this shows the tales in HTML
		for(int i = 0; i < sizetales; i++){
			taleInHtmlCode += "Title: " + tales.get(i).getTitle() + "<br />";
			taleInHtmlCode += "Tale: " + tales.get(i).getTale() + "<br />";
			taleInHtmlCode += "Creation date: " + 
					tales.get(i).getCreationDate().toString() + "<br />";
			taleInHtmlCode += 
					"<input type='button' value='Delete!' onClick='deleteTale(" 
							+ tales.get(i).getId() + ")'</input>";
			taleInHtmlCode += 
					"<input type='button' value='Update!' onClick='updateTale("
							+ tales.get(i).getId() + ")'</input>";
			taleInHtmlCode += "<br />" + "<br />" + "<br />";
		}
		
		return taleInHtmlCode;
	}
	
}
